package com.lcdpg.lcdp.auth.service.impl;

import com.lcdpg.lcdp.auth.dao.UserMapper;
import com.lcdpg.lcdp.auth.domain.LoginRequest;
import com.lcdpg.lcdp.auth.model.User;
import com.lcdpg.lcdp.auth.service.AuthService;
import com.lcdpg.lcdp.auth.utils.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName AuthServiceImpl.java
 * @Description TODO
 * @createTime 2025年05月23日 17:17:00
 */
@Service
public class AuthServiceImpl implements AuthService {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    @Autowired
    public AuthServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public String login(LoginRequest request) throws AuthenticationException {
        // 1. 查询用户


        User user = Optional.ofNullable(userMapper.selectByMap(Map.of("username",request.getUsername())))
                .filter(users -> !users.isEmpty())
                .map(users -> users.get(0))
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));

        // 2. 校验密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }

        // 3. 生成JWT令牌
        return jwtUtil.generateToken(user.getUsername());
    }
}
